package com.xxh.basecrudframework.controller;


import com.xxh.basecrudframework.common.Result;
import com.xxh.basecrudframework.common.dto.UserDTO;
import com.xxh.basecrudframework.common.entity.User;
import com.xxh.basecrudframework.common.param.UserPARAM;
import com.xxh.basecrudframework.controller.common.BaseController;
import com.xxh.basecrudframework.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;

@RestController
@RequestMapping(value = "/user")
@Api(tags = "用户模块接口")
@Slf4j
public class UserController extends BaseController<User,UserDTO,UserPARAM,UserService> {
    @Resource
    private UserService userService;


    @ApiOperation(value = "添加用户")
    @PostMapping(value = "/add")
    public Result<UserDTO> add(@RequestBody @Validated UserPARAM userPARAM){
        User user = paramToEntity(userPARAM);
        User oldUsername = userService.getByUsername(user.getUsername());
        Assert.isNull(oldUsername, "添加失败，用户名重复");
        userService.save(user);
        return Result.success(entityToDto(user));
    }

    @ApiOperation(value = "更新用户")
    @PostMapping(value = "/update")
    public Result<UserDTO> update(@RequestBody @Validated UserPARAM userPARAM){
        User user = paramToEntity(userPARAM);
        User oldUsername = userService.getByUsername(user.getUsername());
        Assert.isNull(oldUsername, "更新失败，用户名重复");
        userService.save(user);
        return Result.success(entityToDto(user));
    }




}
